package com.zlm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlm.common.Result;
import com.zlm.entity.Category;
import com.zlm.entity.Employee;
import com.zlm.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜品分类  川菜，粤菜这些
 */


@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public Result save(@RequestBody Category category) {
        boolean save = categoryService.save(category);
        if (!save) {
            return Result.error("服务器异常,新增分类失败");
        }
        return Result.success("新增分类成功");
    }


    /**
     * 菜品分类的分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize) {
        log.info("page={},size={}", page, pageSize);

        // 构造分页构造器
        Page<Category> pageInfo = new Page(page, pageSize);
        // 构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        // 添加排序条件 根据sort来排序
        queryWrapper.orderByAsc(Category::getSort);


        // 添加排序条件
        queryWrapper.orderByDesc(Category::getUpdateTime);

        // 执行查询
        // 查询到的就放在了pageinfo里面了
        categoryService.page(pageInfo, queryWrapper);

        return Result.success(pageInfo);
    }

    /**
     * 根据id来删除数据
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result deleteById(Long ids) {
        return categoryService.remove(ids);
    }


    /**
     * 根据id来修改分类信息
     *
     * @param category
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Category category) {
        log.info("修改分类信息：{}", category);
        boolean b = categoryService.updateById(category);
        if (!b) {
            return Result.error("服务器发生异常,修改分类失败");
        }

        return Result.success("修改分类成功");

    }

    /**
     * 根据条件查询菜品分类数据
     *
     * @param category
     * @return
     */
    @GetMapping("/list")
    public Result list(Category category) {
        // 条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 添加条件
        lambdaQueryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        // 添加排序条件
        // 第二排序条件就是根据更新时间来的
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lambdaQueryWrapper);

        return Result.success(list);
    }
}
